#include"socketio.hh"
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>


//构造
SockIo::SockIo(int fd)
    :_fd(fd)
{}

//析构
SockIo::~SockIo()
{}

//读取数据
int SockIo::readn(int size,char*  buf)
{
    int left =size;
    int ret =0;
    char* ptr= buf;
    while(left>0)
    {
        ret = read(_fd,ptr,left);
        if(ret ==-1&& errno ==EINTR)
        {
            continue;
        }
        else if(ret == -1)
        {
            perror(" read error -1");
            return -1;
        }
        if(ret==0)
        {
            break;
        }
        else
        {
            ptr += ret;
            left -=ret;
        }
    }
        return size-left;
}

int SockIo::write(int size,const char*  buf)
{
    int left =size;
    int ret =0;
 const   char* ptr= buf;
    while(left>0)
    {
        ret = ::write(_fd,ptr,left);
        if(ret ==-1&& errno ==EINTR)
        {
            continue;
        }
        else if(ret == -1)
        {
            perror(" read error -1");
            return -1;
        }
        if(ret==0)
        {
            break;
        }
        else
        {
            ptr += ret;
            left -=ret;
        }
    }
        return size-left;
}

int SockIo::readline(int size,char* buf)
{

    int left =size-1;
    int ret =0;
    char* ptr= buf;
    int all=0;
    while(left>0)
    {
         ret = recv( _fd , ptr ,left , MSG_PEEK);
        if(ret ==-1&& errno ==EINTR)
        {
            continue;
        }
        else if(ret == -1)
        {
            perror(" read error -1");
            return -1;
        }
        if(ret==0)
        {
            break;
        }
        else
        {
            for(int i =0; i< ret ;++i)
            {
                if(ptr[i]=='\n')
                {
                    int  sz= i+ 1;
                    readn(sz , ptr);
                    ptr += sz;
                    return all+sz;
                }
            }
            readn(ret, ptr);
            ptr += ret;
            left -=ret;
            all += ret;
        }
    }
    *ptr='\n';
        return all-left;

}
